package com.gradecak.alfresco.mvc.aop;

import java.util.Arrays;

import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator;

public class PackageAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {

  private static final long serialVersionUID = -1219238254256448615L;

  private String basePackage;
  private String[] interceptorNames = new String[0];

  @Override
  protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) {
    if (this.basePackage != null) {
      if(beanClass != null && beanClass.getPackage() != null && beanClass.getPackage().getName().equals(basePackage)) {
        Object[] advicesAndAdvisorsForBean = super.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
        return advicesAndAdvisorsForBean;
      }
    }
    return DO_NOT_PROXY;
  }

  protected boolean isEligibleAdvisorBean(String beanName) {
    boolean contained = Arrays.asList(interceptorNames).contains(beanName);
    return contained;
  }

  public void setInterceptorNames(String[] interceptorNames) {
    this.interceptorNames = interceptorNames;
    super.setInterceptorNames(this.interceptorNames);
  }

  public void setBasePackage(String basePackage) {
    this.basePackage = basePackage;
  }
}
